package hot100;

import java.util.HashMap;

public class g14_LRU缓存 {
    static class Node {
        Node prev;
        Node next;
        int key;
        int value;

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    static class DoublyLinkedList {
        private final Node head;
        private final Node tail;

        DoublyLinkedList() {
            head = tail = new Node(-1, -1);
            head.next = tail;
            tail.prev = head;
        }

        void addFirst(Node newFirst) {
            Node oldFirst = head.next;
            newFirst.prev = head;
            newFirst.next = oldFirst;
            head.next = newFirst;
            oldFirst.prev = newFirst;
        }

        void remove(Node node) {
            Node prev = node.prev;
            Node next = node.next;
            prev.next = next;
            next.prev = prev;
        }

        Node removeLast() {
            Node last = tail.prev;
            remove(last);
            return last;
        }

    }

    private final HashMap<Integer, Node> map = new HashMap<>();
    private final DoublyLinkedList linkedList = new DoublyLinkedList();
    private final int capacity;

    public g14_LRU缓存(int capacity) {
        this.capacity = capacity;
    }

    public int get(int key) {
        Node node = map.get(key);
        if (node == null) {
            return -1;
        }
        linkedList.remove(node);
        linkedList.addFirst(node);
        return node.value;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            node.value = value;
            linkedList.remove(node);
            linkedList.addFirst(node);
        } else {
            Node node = new Node(key, value);
            map.put(key, node);
            linkedList.addFirst(node);
            if (map.size() > capacity) {
                Node last = linkedList.removeLast();
                map.remove(last.key);
            }
        }
    }
}
